<?php

namespace app\api\logic;


use think\facade\Db;
use app\data\util\HttpUtil;
use think\exception\ValidateException;
use think\facade\Cache;
use app\api\logic\FeiShuTalkLogic;
use app\api\logic\LinXingOrderLogic;
use app\purchase\logic\PlanSuggestLogic;
use app\api\logic\FeiShuMessageLogic;
use think\cache\driver\Redis;

class ApiStockUpLogic extends BasicLogic
{
    public function __construct()
    {

    }

    /**
    * @desc    仓库安全库存
    * @date    2025/06/09
    * @msg    //爆款是7天，潜力款3天，新品3天，长尾款1天
    * @author  zhangheng
    */
    public function SafetyStock($params=[])
    {
        //固定7天
        $spu = $params['spu'] ?? "";
        if (empty($spu)) {
            $return = [
                'hot_type' => 4,
                'suggest_days' => 7,
            ];
            return $return;
        }
        //查询
        $sku_rank = Db::name('sku_rank')
            ->field('rank')
            ->where('spu',$spu)
            ->find();
        $rank = $sku_rank['rank'] ?? 0;
        //热销
        if(5 >= $rank && $rank >= 1){
            $return = [
                'hot_type' => 1,
                'suggest_days' => 7,
            ];
            return $return;
        }
        //潜力款
        if(10 >= $rank && $rank >= 6){
            $return = [
                'hot_type' => 2,
                'suggest_days' => 7,
            ];
            return $return;
        }
        //新品--3天
        $product = Db::name('product')
            ->field('product_new')
            ->where('spu',$spu)
            ->find();
        $product_new = $product['product_new'] ?? 0;
        if($product_new == 1){
            $return = [
                'hot_type' => 2,
                'suggest_days' => 7,
            ];
            return $return;
        }
        //中长尾款
        $return = [
            'hot_type' => 4,
            'suggest_days' => 7,
        ];
        return $return;
    }

    /**
    * @desc    平均日销
    * @date    2025/06/09
    * 仓库安全库存数量
    * @param   array $params  sku
    * @return  array
    * @author  zhangheng
    */
    public function SafetyStockQuantity($params=[])
    {
        //仓库安全库存天数
        $is_last = $params['is_last'] ?? 0;

        //仓库安全库存天数
        $SafetyStock = $params['SafetyStock'];
        $sku = $params['sku'];
        if(empty($sku)) {
            return 0;
        }
        if(empty($SafetyStock)) {
            return 0;
        }
        
        $where[]  = ['new_sku', '=', $sku];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        //日期
        $Today = date('Y-m-d', time() - timezone());
        if($is_last == 1){
            $yesterday = date('Y-m-d', strtotime('-'.$is_last.' day') - timezone());
        }
        $yesterday = date('Y-m-d', strtotime('-'.$SafetyStock.' day') - timezone());
        $midnightToday = strtotime($yesterday);
        $endOfYesterday  = strtotime($Today);
        $where[]  = ['createtime', '>=', $midnightToday];
        $where[]  = ['createtime', '<', $endOfYesterday];
        $lists = Db::name('order_skuinfo')
            ->field('sum(realcount) as count,new_sku as sku')
            ->where($where)
            ->group('new_sku')
            ->find();
        return $lists['count'] ?? 0;
    }

    /**
    * @desc    平均日销
    * @date    2025/06/09
    * @author  zhangheng
    */
    public function AverageDailySales($params=[])
    {
        $safe_quantity = $params['safe_quantity'];
        $suggest_days = $params['suggest_days'];

        if ($safe_quantity <= 0) {
            return 0;
        }
        if ($suggest_days <= 0) {
            return 0;
        }
        //平均日销=安全库存数量/仓库安全库存天数
        $DailySales = number_format((float)$safe_quantity / (float)$suggest_days, 2, '.', '');
        return ceil($DailySales);
    }


    /**
    * @desc    做货周期默认12天
    * @date    2025/06/09
    * @author  zhangheng
    */
    public function ProductionCycle($spu='')
    {
        $purchase_suggest_plan = Db::name('purchase_suggest_plan_produce')->field('produce_days')->where('spu',$spu)->find();
        return $purchase_suggest_plan['produce_days'] ?? 12;
    }


    /**
     * @desc    建议幅值默认1
     * @date    2025/06/09
     * @author  zhangheng
     */
    public function ProductionRate($spu='')
    {
        $purchase_suggest_Rate = Db::name('purchase_suggest_plan_produce')->field('suggest_rate')->where('spu',$spu)->find();
        return $purchase_suggest_Rate['suggest_rate'] ?? 1;
    }


    /**
    * @desc    物流运输默认3天
    * @date    2025/06/09
    * @author  zhangheng
    */
    public function Logistics($params=[])
    {
        //TODO 待定
        return 3;
    }

    /**
    * @desc    订单未发数量
    * @date    2025/06/09
    * @author  zhangheng
    */
    public function UnshippedQuantity($params=[])
    {
        //仓库安全库存天数
        $SafetyStock = $params['SafetyStock'] ?? "7";

        $sku = $params['sku'] ?? "bra111-caramel-D";
        
        $where[]  = ['a.new_sku', '=', $sku]; 
        $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid"]];
        $where[]  = ['c.fulfillment_status', '<>', "fulfilled"];
        //日期
        $Today = date('Y-m-d', strtotime('-1 day') - timezone());
        $yesterday = date('Y-m-d', strtotime('-'.$SafetyStock.' day') - timezone());
        $midnightToday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($Today . ' 23:59:59');
        $where[]  = ['c.createtime', '>=', $midnightToday];
        $where[]  = ['c.createtime', '<=', $endOfYesterday];
        // halt($where);
        $lists = Db::name('order_skuinfo')
            ->field('
                sum(a.realcount) as count,
                a.new_sku as sku
            ')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->group('a.new_sku')
            ->order('count desc')
            ->select()->toarray();
        $Quantity = $lists[0]['count'] ?? 0;
        return $Quantity;
    }

    /**
    * @desc    采购在途数量
    * @date    2025/06/09
    * @author  zhangheng
    */
    public function ProcurementInTransit($params=[])
    {
        //TODO 待定
        return 0;
    }

    /**
    * @desc    可用库存数量
    * @date    2025/06/09
    * @author  zhangheng
    */
    public function AvailableInventory($params=[])
    {
        //TODO 待定
        return 0;
    }

    /**
    * @desc    补货数量
    * @date    2025/06/09
    * @author  zhangheng
    */
    public function Replenishment($params=[])
    {
        //补货数量 =（做货周期+物流运输+仓库安全库存）*平均日销+订单未发数量-采购在途数量-可用库存数量

        //做货周期
        $ProductionCycle = $this->ProductionCycle();

        //物流运输
        $Logistics = $this->Logistics();

        //仓库安全库存
        $SafetyStock = $this->SafetyStock();

        //平均日销
        $params['sku'] = "bra111-caramel-D";
        $AverageDailySales = $this->AverageDailySales();

        //订单未发数量
        $UnshippedQuantity = $this->UnshippedQuantity();

        //采购在途数量
        $ProcurementInTransit = $this->ProcurementInTransit();

        //可用库存数量
        $AvailableInventory = $this->AvailableInventory();

        if (($ProductionCycle + $Logistics + $SafetyStock) <= 0) {
            return 0;
        }
        if ($AverageDailySales <= 0) {
            return 0;
        }
        
        //补货数量 =（做货周期+物流运输+仓库安全库存）*平均日销+订单未发数量-采购在途数量-可用库存数量
        $Replenishment = number_format((float)($ProductionCycle + $Logistics + $SafetyStock) * (float)$AverageDailySales + (float)$UnshippedQuantity - (float)$ProcurementInTransit - (float)$AvailableInventory, 0, '.', '');
        return $Replenishment;
    }


    /**
    * @desc    补单提醒
    * @date    2025/06/09
    * @author  zhangheng
    */
    public function SupplementReminder($params=[])
    {
        // 补单提醒：可用库存数量（实际库存+采购在途）数量小于整单货期以下，补单提醒

        //做货周期
        $ProductionCycle = $this->ProductionCycle();

        //物流运输
        $Logistics = $this->Logistics();

        //平均日销
        $params['sku'] = "bra111-caramel-D";
        $AverageDailySales = $this->AverageDailySales();

        if (($ProductionCycle + $Logistics) <= 0) {
            $WarningInventory = 0;
        }
        if ($AverageDailySales <= 0) {
            $WarningInventory = 0;
        }
        
        // 补单提醒：可用库存数量（实际库存+采购在途）数量小于整单货期以下，补单提醒
        $WarningInventory = number_format((float)($ProductionCycle + $Logistics) * (float)$AverageDailySales, 0, '.', '');

        //采购在途数量
        $ProcurementInTransit = $this->ProcurementInTransit();

        //可用库存数量
        $AvailableInventory = $this->AvailableInventory();

        $SupplementReminder = number_format((float)$ProcurementInTransit + (float)$AvailableInventory - (float)$WarningInventory, 0, '.', '');
        if  ($SupplementReminder <= 0) {
            //飞书提醒
            // $FeiShuMessageLogic = new FeiShuMessageLogic();
            // $system_admin = Db::name('system_admin')->field('open_id')->where('id',2)->find();
            // $open_id = $system_admin['open_id'] ?? 0;
            // if($open_id){
            //     $datamsg = [
            //         'message' => "需要补货",
            //         'open_id' => $open_id,
            //     ];
            //     $FeiShuMessageLogic->send_message($datamsg);
            // }
        }
        return "完成";
    }

    /**
    * @desc    每日洗数据--sku销量排行榜
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function sku_rank()
    {
        //30天内销量排行
        $where = [];
        $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        //日期
        $Today = date('Y-m-d', strtotime('-1 day') - timezone());
        $yesterday = date('Y-m-d', strtotime('-32 day') - timezone());
        $midnightToday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($Today . ' 23:59:59');
        $where[]  = ['a.createtime', '>=', $midnightToday];
        $where[]  = ['a.createtime', '<=', $endOfYesterday];
        // halt($where);
        $lists = Db::name('order_skuinfo')
            ->field('
                count(a.id) as nums,
                a.spu,a.new_sku as seller_sku
            ')
            ->alias('a')
            ->where($where)
            ->group('a.spu')
            ->order('nums desc')
            ->limit(15)
            ->select()->toarray();
        foreach ($lists as $k=>$v) {
            //标记排行
            $lists[$k]['rank'] = $k+1;
            $lists[$k]['create_time'] = date('Y-m-d H:i:s');
        }
        // halt($lists);
        
        Db::name('sku_rank')->where('id',"<>",0)->delete();
        Db::name('sku_rank')->insertAll($lists);
    }

    /**
    * @desc    每日洗数据--补货备货
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function purchase_suggest_plan()
    {

        //update 2025-06-14  qu_purchase_suggest_plan，获取最新的;
        Db::execute('TRUNCATE TABLE qu_purchase_suggest_plan');
        Db::execute('TRUNCATE TABLE qu_purchase_suggest_plan_spu');
        //日期
        $Today = date('Y-m-d', strtotime('-1 day') - timezone());
        $yesterday = date('Y-m-d', strtotime('-7 day') - timezone());
        $midnightToday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($Today . ' 23:59:59');
        $where[]  = ['createtime', '>=', $midnightToday];
        $where[]  = ['createtime', '<=', $endOfYesterday];
        $where[]  = ['is_seel', '<>',1];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $lists = Db::name('order_skuinfo')
            ->field('spu,new_sku as sku')
            ->where($where)
            ->group('new_sku')
            ->select()
            ->toArray();
        $count = count($lists);
        $spus = array_column($lists,'spu');
        $spus = array_values(array_unique($spus));
        //存储spu信息;
        self::add_spu($spus);
        $executedCount = 0;
        foreach($lists as $v){
            //查看sku的可用数量
            $can_use_nums = self::get_can_use_nums($v);
            if($can_use_nums==2) continue;
            //添加数据
            $insert_info  = $this->purchase_suggest($v);
            Db::name('purchase_suggest_plan')->insert($insert_info);
            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----SKU：'. $v['sku'] . ",已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }

    }


    /**
     * @desc    备货建议数量spu
     * @author  luckyXiong
     * @date    2024-12-06
     */
    public function add_spu($spus){
        $field    = 'spu,sum(all_inventory_quantity) as all_inventory_quantity,sum(on_way_quantity) as on_way_quantity,sum(not_send_quantity) as not_send_quantity';
        $all_list = Db::name('product_inventory')->field($field)
            ->whereIn('spu',$spus)
            ->group('spu')
            ->select()->toArray();
        $all_list_map = array_column($all_list,null,'spu');
        $nums_day7s = self::get_days7_sku($spus);
        $nums_info_map  = array_column($nums_day7s,'skuquantity','spu');
        $arr = [];
        foreach($spus as $k=>$v){
            //供应商;
            $supply_info = self::supply_info(['spu'=>$v]);
            $supply_id   = $supply_info['id'] ?? 0;
            $supply_name = $supply_info['supply_name'] ?? "";

            $nums_day7s_value               = $nums_info_map[$v]??'0';
            $all_info                       = $all_list_map[$v]??[];
            $arr[$k]['spu']                 = $v;
            $arr[$k]['supply_id']           = $supply_id;
            $arr[$k]['supply_name']         = $supply_name;
            $arr[$k]['all_inventory_quantity'] = $all_info['all_inventory_quantity']??0;
            $arr[$k]['on_way_quantity']    = $all_info['on_way_quantity']??0;
            $arr[$k]['not_send_quantity']  = $all_info['not_send_quantity']??0;
            $sku_1days                     = ceil($nums_day7s_value/7);
            $arr[$k]['sku_1days']          = $sku_1days;
            $arr[$k]['create_time']        = date("Y-m-d H:i:s", time());
        }
        Db::name('purchase_suggest_plan_spu')->insertAll($arr);
    }

    public function get_days7_sku($spus){
        $where     = [];
        $yesterday = strtotime(date('Y-m-d', time() - timezone()));
        $yesterdayEnd = strtotime(date('Y-m-d', strtotime('-7 day') - timezone()));
        $where[] = ['createtime', '<', $yesterday];
        $where[] = ['createtime', '>=', $yesterdayEnd];
        $where[] = ['is_seel', '=', 0];
        $where[] = ['spu', 'in', $spus];
        $field      = 'sum(realcount) AS skuquantity,spu';
        return Db::name('order_skuinfo')->where($where)->field($field)
               ->group('spu')
               ->select()->toArray();
    }






    public function get_can_use_nums($info =[]){
        $produce_days = $this->ProductionCycle($info['spu']);
        $sku_7days    = $this->SafetyStockQuantity(['sku'=>$info['sku'],'SafetyStock'=>7]);
        $sku_1days    = ceil($sku_7days/7);
        $can_use_num  = 0;
        $all_inventory_quantity = Db::name('product_inventory')->where(['seller_sku'=>$info['sku']])->value('all_inventory_quantity');
        $all_inventory_quantity = $all_inventory_quantity ?:0;
        if($sku_1days){
            $can_use_num  = $sku_1days*($produce_days+3);
        }

        // 1:补货, 2:不补
        if($all_inventory_quantity<=$can_use_num && $sku_1days){
              return 1 ;
        }else{
              return 2 ;
        }
    }







    
    /**
    * @desc    单独更新备货建议
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function UpdatePurchaseSuggest($id)
    {
        if(empty($id)){
            return json(DefaultResponse(201, false, '参数错误!', null));
        }
        $info = Db::name('purchase_suggest_plan')->where('id',$id)->find();
        if(empty($info)){
            return json(DefaultResponse(201, false, '数据为空!', null));
        }
        $insert = $this->purchase_suggest($info);
        Db::name('purchase_suggest_plan')->where('id',$id)->update($insert);
        return json(DefaultResponse(200, true, '操作成功!', null));
    }
    

    /**
    * @desc    添加数据
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function purchase_suggest($v)
    {

        $spu = $v['spu'];
        // 安全库存天数
        //爆款是7天，潜力款3天，新品3天，长尾款1天
        $params = [
            'spu' => $spu,
        ];

        $SafetyStock = $this->SafetyStock($params);

        $hot_type = $SafetyStock['hot_type'];
        $suggest_days = $SafetyStock['suggest_days'];
        
        // 库存数量 在途数量
        $params = [
            'sku' => $v['sku'],
        ];
        $product_inventory = $this->product_inventory($params);
        //总库存数量
        $inventory_quantity = $product_inventory['all_inventory_quantity'] ?? 0;
        //可用库存数量
        $available_quantity = $product_inventory['inventory_quantity'] ?? 0;
        //在途数量
        $on_way_quantity    = $product_inventory['on_way_quantity'] ?? 0;
        //未发数量
        $not_send_quantity  = $product_inventory['not_send_quantity'] ?? 0;


        // 3天的销量
        $params = [
            'sku' => $v['sku'],
            'SafetyStock' => 3,
        ];
        $sku_3days = $this->SafetyStockQuantity($params);
        // 3天的销量

        // 7天的销量
        $params = [
            'sku' => $v['sku'],
            'SafetyStock' => 7,
        ];
        $sku_7days = $this->SafetyStockQuantity($params);
        // 7天的销量

        // 日均销量
        $sku_1days = 0;
        if($sku_7days > 0){

            $sku_1days = number_format((float)$sku_7days / 7, 2, '.', '');
        }
        // 日销量

        // 前一天的--日均销量
        $params = [
            'sku' => $v['sku'],
            'SafetyStock' => 8,
            'is_last' => 1,
        ];
        $last_sku_7days = $this->SafetyStockQuantity($params);
        $last_sku_1days = 0;
        if($last_sku_7days > 0){
            $last_sku_1days = number_format((float)$last_sku_7days / 7, 2, '.', '');
        }
        // 前一天的--日均销量

        //前一天和当天的sku增长比例
        $increase_rate = 0;
        if($sku_1days > 0 && $last_sku_1days > 0){
            $increase_rate = number_format((float)($sku_1days - $last_sku_1days) / $last_sku_1days * 100, 2, '.', '');
            if($increase_rate < 0){
                $increase_rate = 0;
            }
        }
        //前一天和当天的sku增长比例

        // 15天的销量
        $params = [
            'sku' => $v['sku'],
            'SafetyStock' => 15,
        ];
        $sku_15days = $this->SafetyStockQuantity($params);
        // 15天的销量

        // 30天的销量
        $params = [
            'sku' => $v['sku'],
            'SafetyStock' => 30,
        ];
        $sku_30days = $this->SafetyStockQuantity($params);
        // 30天的销量

        // 安全库存数
        $params = [
            'sku' => $v['sku'],
            'SafetyStock' => $suggest_days,
        ];
        $safe_quantity = $this->SafetyStockQuantity($params);
        //做货天数
        $produce_days = $this->ProductionCycle($spu);
        //建议幅值;
        $suggest_rate = self::ProductionRate($spu);
        // 物流天数
        $track_days = 3;
        // 图片
        $params = [
            'spu' => $v['spu'],
        ];
        $image_url = $this->image_url($params);


        // 供应商
        $params = [
            'spu' => $v['spu'],
        ];

        //供应商;
        $supply_info = $this->supply_info($params);
        $supply_id = $supply_info['id'] ?? 0;
        $supply_name = $supply_info['supply_name'] ?? "";

        // 补货数量
        //补货数量 =（做货周期+物流运输+仓库安全库存）*平均日销+订单未发数量-(采购在途数量-可用库存数量)
        $suggest_sku_nums = 0;
        $status = 2;
        if (($produce_days + $track_days + $suggest_days) > 0 && $sku_1days > 0) {
            $suggest_sku_nums = ($produce_days + $track_days + $suggest_days) * $sku_1days + $not_send_quantity - ($on_way_quantity+$inventory_quantity);
            if($suggest_sku_nums <= 0){
                $suggest_sku_nums = 0;
                $status = 2;
            }else{
                //乘以对应的幅值比例;
                $suggest_sku_nums = ceil($suggest_sku_nums*$suggest_rate);
                $status = 1;
            }
        }
        //类型
        $product_type = (new LinXingOrderLogic())->get_product_type(['spu'=>$v['spu']]);
        //找到尺码
        try{ 
            $sizeinfo = (new PlanSuggestLogic())->get_size($v['sku'],$product_type);
        }catch(\Exception $e){
            echo $v['sku']."报错：".$e->getMessage();
        }
        $color = $sizeinfo['color'] ?? '';
        $size = $sizeinfo['size'] ?? '';
        $cup = $sizeinfo['cup'] ?? '';



        $insert = [
            'color'=>$color,
            'size' =>$size,
            'cup'  =>$cup,
            'spu' => $v['spu'] ?? '',
            'seller_sku' => $v['sku'] ?? '',
            'hot_type' => $hot_type,
            'suggest_days' => $suggest_days,
            'status' => $status,
            'inventory_quantity' => $inventory_quantity,
            'available_quantity' => $available_quantity,
            'on_way_quantity' => $on_way_quantity,
            'safe_quantity' => $safe_quantity,
            'not_send_quantity' => $not_send_quantity,
            'sku_1days' => $sku_1days,
            'last_sku_1days' => $last_sku_1days,
            'increase_rate' => $increase_rate,
            'sku_3days' => $sku_3days,
            'sku_7days' => $sku_7days,
            'sku_15days' => $sku_15days,
            'sku_30days' => $sku_30days,
            'produce_days' => $produce_days,
            'track_days' => $track_days,
            'suggest_rate' => $suggest_rate,
            'image_url' => $image_url,
            'supply_id' => $supply_id,
            'supply_name' => $supply_name,
            'product_type' => $product_type,
            'suggest_sku_nums' => $suggest_sku_nums,
            'update_time' => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s'),
        ];

        return $insert;
    }
    

    /**
    * @desc    库存数量
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function product_inventory($params)
    {
        $sku = $params['sku'] ?? "";
        if(empty($sku)) {
            return [];
        }
        $product_inventory = Db::name('product_inventory')->where('seller_sku',$sku)->find();
        return $product_inventory;
    }
    
    /**
    * @desc    图片地址
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function image_url($params)
    {
        $spu = $params['spu'] ?? "";
        if(empty($spu)) {
            return "";
        }
        $product = Db::name('product')->where('spu',$spu)->find();
        $product_images = $product['product_images'] ?? "";
        if(empty($product_images)) {
            return "";
        }
        $product_images = json_decode($product_images,true);
        $image_url = $product_images[0] ?? "";
        return $image_url;
    }

    /**
    * @desc    供应商
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function supply_info($params)
    {
        $spu = $params['spu'] ?? "";
        if(empty($spu)) {
            return [];
        }
        $supply_info = Db::name('supply_info')
            ->field('b.id,b.supply_name')
            ->alias('a')
            ->join('qu_supply b','b.id = a.supply_id', 'left')
            ->where('a.spu', $spu)
            ->order('a.created_time desc')
            ->find();
        return $supply_info;
    }

    


    /**
     * @desc   获取在线表格数据
     * @author luckyXiong
     * @date   2024-10-24
     */
    public function getTablerecordsPants($params=[]){
        $basic_url             = Config('Logisticskey.fei_shu.basic_url');
        $get_table_list        = Config('Logisticskey.fei_shu.get_table_list');
        $table_id              = $params['table_id']??'tblKsPAc00UyxaBE';
        $table_token           = $params['table_token']??'Y0sWbMQZGaDTwdsf1Sdc04junGe';
        if(!$table_id)           $this->jsonMessage(201, false, 'table_id不能为空!', null);
        $token                 = self::get_app_access_token();
        $url                   = $basic_url.$get_table_list.$table_token.'/tables/'.$table_id.'/records';
        $res                   = HttpUtil::getFeiShu($url,$token,[]);
        if($res['code']==0){
            $list = $res['data']['items'];
            $arr = [];
            foreach($list as $v){
                    $info = $v['fields'];
                    if(!isset($info['SPU']) || !$info['SPU']) continue;
                    $values =  self::change_data($info);
                    if($values){
                        $arr[] = $values;
                    }
            }
            // halt($arr);
            //数据批量存入库
            if($arr){
                Db::name('feishu_purchase')->where('id',"<>",0)->delete();
                Db::name('feishu_purchase')->insertAll($arr);
            }
            echo $res['msg']. PHP_EOL;
            // return      $this->jsonMessage(200,true,$res['msg'],null);
        }else{
            echo $res['msg']. PHP_EOL;
            // return      $this->jsonMessage(201,false,$res['msg'],null);
        }
    }



    /**
     * @desc   获取app_token
     * @author xx
     * @date 2024-09-24
     */
    public function get_app_access_token(){
        $key        = "app_access_token_feishu";
        $token      = Cache::store('redis')->get($key);
        if(empty($token)){
            $app_id                = Config('Logisticskey.fei_shu.app_id');
            $app_secret            = Config('Logisticskey.fei_shu.app_secret');
            $basic_url             = Config('Logisticskey.fei_shu.basic_url');
            $app_access_token_url  = Config('Logisticskey.fei_shu.app_access_token');
            $url                   = $basic_url.$app_access_token_url;
            $data                  = [
                'app_id'    => $app_id,
                'app_secret'=> $app_secret,
            ];
            $response = HttpUtil::postDataCurl($url, $data);
            $token    = $response['app_access_token']??'';
            $expire   = $response['expire']??'';
            Cache::store('redis')->set($key, $token,$expire-3);
        }
        return  $token;
    }



    /**
     * @desc   整理数据格式
     * @author luckyXiong
     * @date   2024-10-25
     */
    private function change_data($info=[]){
        $spu     = $info['SPU']??'';
        $spu = trim($spu);
        $create_time     = $info['下单日期']??"";
        if(!empty($create_time)){
            $create_time = date('Y-m-d H:i:s',$create_time/1000);
        }
        $delivery_time     = $info['仓库反馈：到仓时间（整单到齐）']??"";
        if(!empty($delivery_time)){
            $delivery_time = date('Y-m-d H:i:s',$delivery_time/1000);
        }
        $admin_name     = $info['人员'][0]['name']??'';
        $admin_name = trim($admin_name);
        $open_id     = $info['人员'][0]['id']??'';
        if(!empty($open_id)){
            $system_admin = Db::name('system_admin')->where('open_id',$open_id)->find();
            $admin_id = $system_admin['id']??0;
        }
        $num     = $info['订单数量']??0;
        $supply_name     = $info['供应商']??'';
        $data =  [
            'spu'                   => $spu,
            'create_time'           => $create_time,
            'delivery_time'         => $delivery_time,
            'admin_name'            => $admin_name,
            'admin_id'              => $admin_id,
            'num'                   => $num,
            'supply_name'           => $supply_name,
        ];
        // $res = Db::name('feishu_purchase')
        //     ->where('spu',$spu)
        //     ->where('admin_name',$admin_name)
        //     ->where('create_time',$create_time)
        //     ->find();
        // if($res){
        //     Db::name('feishu_purchase')->where('id',$res['id'])->update($data);
        //     return  '';
        // }else{
            return  $data;
        // }
    }
    
    /**
    * @desc    每日维护库存需要飞书提醒到个人
    * @author  zhangheng
    */
    public function product_inventory_remind()
    {
        $product_inventory = Db::name('product_inventory')->field('update_time')->where('id','>',0)->order('update_time desc')->find();
        $update_time = $product_inventory['update_time']??0;
        //最后一次更新时间小于今天
        if(strtotime($update_time) < strtotime(date('Y-m-d'))){
            echo "今日还没有更新库存";
            //提醒
            $FeiShuMessageLogic = new FeiShuMessageLogic();
            $system_admin = Db::name('system_admin')->field('open_id')->where('id',93)->find();
            $open_id = $system_admin['open_id'] ?? 0;
            if($open_id){
                $datamsg = [
                    'message' => "今日还没有更新库存",
                    'open_id' => $open_id,
                ];
                $FeiShuMessageLogic->send_message($datamsg);
            }
        }else{
            echo "今日已更新库存".PHP_EOL;
        }
    }

    /**
    * @desc    飞书发预警信息-建议备货量
    * @author  zhangheng
    */
    public function SuggestedStockingQuantity()
    {
        // 1.sku每日出单30件以上的
        // 2.昨日今天的日均涨幅超过10%
        $count = Db::name('purchase_suggest_plan')
            ->where('sku_1days','>=',30)
            ->where('increase_rate','>=',10)
            ->count();
        echo $count."条数据需要提醒".PHP_EOL;

        $plans = Db::name('purchase_suggest_plan')
            ->where('sku_1days','>=',30)
            ->where('increase_rate','>=',10)
            ->select()->toarray();

        foreach ($plans as $k=>$v) {
            if (strpos($v['spu'],'bra') !== false || strpos($v['spu'],'nip') !== false) {
                $admin_id = 70;
                $this->FeiShuMessages($v,$admin_id);
                echo 'SKU:'.$v['seller_sku'].",给李玉洁发消息". PHP_EOL;
                continue;
            }
            if (strpos($v['spu'],'sha') !== false) {
                $admin_id = 125;
                $this->FeiShuMessages($v,$admin_id);
                echo 'SKU:'.$v['seller_sku'].",给王斯发消息". PHP_EOL;
                continue;
            }
            if (strpos($v['spu'],'pan') !== false) {
                $admin_id = 120;
                $this->FeiShuMessages($v,$admin_id);
                echo 'SKU:'.$v['seller_sku'].",给张璟仪发消息". PHP_EOL;
                continue;
            }
            if (strpos($v['spu'],'swim') !== false) {
                $admin_id = 73;
                $this->FeiShuMessages($v,$admin_id);
                echo 'SKU:'.$v['seller_sku'].",给王卉丹发消息". PHP_EOL;
                continue;
            }
            
        }
            
    }

    /**
    * @desc    实时记录今天业绩
    */
    public function FeiShuMessages($v,$admin_id)
    {
        //提醒
        $FeiShuMessageLogic = new FeiShuMessageLogic();
        $system_admin = Db::name('system_admin')->field('open_id')->where('id',$admin_id)->find();
        $open_id = $system_admin['open_id'] ?? 0;
        if($open_id){

            $msg = '';
            $msg = "【".date('Y-m-d H:i')."】" . PHP_EOL;
            $msg = $msg. "【SKU备货预警】" . PHP_EOL;

            $datamsg = [
                'message' => $msg.'SKU:'.$v['seller_sku']."---日均销量:".$v['sku_1days']."单---比昨日涨幅:".$v['increase_rate']."%",
                'open_id' => $open_id,
            ];
            $FeiShuMessageLogic->send_message($datamsg);
        }
        return true;
    }
        
        
    
    /**
    * @desc    每日洗数据--每日可用库存--新规则
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function inventory_quantity_new()
    {
        //一个小时之前
        $time = time() - 60*12;
        // $time = time() - 3600*24*90;
        $where[]  = ['update_time', '>', date('Y-m-d H:i:s', $time)];
        $lists = Db::name('product_inventory')
            ->field('
                id,
                all_inventory_quantity,
                inventory_quantity,not_send_quantity
            ')
            ->where($where)
            ->order('id desc')
            ->select()->toarray();

        $count = count($lists);
        if($count <= 0){
            echo '没有数据'.PHP_EOL;
        };
        
        $executedCount = 0;
        foreach($lists as $k=>$v){
            if((int)$v['all_inventory_quantity'] > (int)$v['not_send_quantity']){
                $inventory_quantity_new = (int)$v['all_inventory_quantity'] - (int)$v['not_send_quantity'];
                $lack_inventory_quantity = 0;
            }else{
                $inventory_quantity_new = 0;
                $lack_inventory_quantity = (int)$v['not_send_quantity'] - (int)$v['all_inventory_quantity'];
            }
            $update = [
                'inventory_quantity_new' => $inventory_quantity_new ?? 0,
                'lack_inventory_quantity' => $lack_inventory_quantity ?? 0,
            ];
            Db::name('product_inventory')->where('id',$v['id'])->update($update);

            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . ",已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
    }


    /**
     * @desc    sku
     * @date    2024/7/16
     */
    public function add_sku_plan($info){
        $can_use_nums = (new ApiStockUpLogic())->get_can_use_nums($info);
        if($can_use_nums==2) return true;
        $insert_info  = $this->purchase_suggest($info);
        Db::name('purchase_suggest_plan')->insert($insert_info);
        return  true;
    }
        
    

}
